// JavaScript Document
const FPSlimit = 30;
var curFPS = 0;
var numFramesDrawn = 0;
var fpsInterval = setInterval(updateFPS, 1000);
var numResourcesLoaded = 0;
var totalResources = 1;
var gameModeSelected = false;
var gameModes = null;
var canvas = null;
var ctx = null;
var images = {};
var grid = 32;
var maxGrid = 48;
var backGrid = 128;
var maxBackGrid = 192;
var offSet = 8;
var backOffset = 32;
var mapLoaded = false;
var contentLoaded = false;
var players = new Array();
var bombs = new Array();
var lvl = 1;
var keys = new Array();
var mapFiles = new Array();
var keylock = new Array();
var booleanMap = [];

window.addEventListener('keydown', keyDown, true);
window.addEventListener('keyup', keyUp, true);
window.addEventListener('blur', canvasLostFocus, true);

window.onload = init;

function init() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext("2d");
    loadContext();
    initGameModes();

    setInterval(gameLoop, 1000 / FPSlimit);
}
function initOnePlayerGame() {
    gameModes = null;
    var p1 = new Player();
    p1.init(uniqueID());
    p1.assignKeys(KeyBoardType.ARROWS);
    players.push(p1);

    var c1 = new SimpleAI();
    c1.init(uniqueID());
    players.push(c1);
}

function initGameModes() {
    gameModes = new GameModes2();
    gameModes.addMode(new Mode2(100, 40, 400, 120, "Player vs Player", GameModeSelection.PLAYERvsPLAYER));
    gameModes.addMode(new Mode2(100, 200, 400, 120, "Player vs Computer", GameModeSelection.PLAYERvsAI));
    gameModes.addMode(new Mode2(100, 340, 400, 120, "Multiplayer", GameModeSelection.MultiPLAYER));
}

function initTwoPlayerGame() {
//    gameModes = null;
    var p1 = new Player2(uniqueID());

    p1.assignKeys(KeyBoardType.WASD);
    players.push(p1);
    createPlayerSideBar(p1);

    var p2 = new Player2(uniqueID());

    p2.assignKeys(KeyBoardType.ARROWS);
    players.push(p2);
    createPlayerSideBar(p2);
    testPlayer2();

}

function testPlayer2(){
    var t = new GameObject2(uniqueID());
    var p3 = new Player2(uniqueID());
    t.toString();
    p3.toString();
}
function loadContext() {
    loadImage("TilesSprite2");
    loadImage("spritesheet1");
    loadImage("backsheet1");
}

level = {
    name:"Error 100 - Level not found",
    map:[],
    spawnPos:{
        "x":0,
        "y":0
    }
};

function canvasLostFocus(evt) {
    keys = new Array();
}

function updateFPS() {
    curFPS = numFramesDrawn;
    numFramesDrawn = 0;
}

function gameLoop() {
    if (contentLoaded && mapLoaded) {
        if (gameModeSelected) {
            update();
            clear();
            draw();
        } else {
            draw();
            gameModes.draw();
            updateGameSelecionKeys();
        }
    } else {
        drawLoading();
    }
}

function update() {
    for (var i = 0; i < players.length; i++) {
        if (players[i].isAlive()) {
            players[i].update();
            updateArrowKeys(players[i]);
        }
    }
    for (i = 0; i < bombs.length; i++) {
        if (bombs[i] != undefined) {
            bombs[i].update();
        }
    }
}

function draw() {
    drawBackground();
    drawWorld();
    for (var i = 0; i < bombs.length; i++) {
        if (bombs[i] != undefined) {
            bombs[i].draw();
        }
    }

    for (var j = 0; j < players.length; j++) {
        if (players[j].isAlive()) {
            // console.log("drawing " +  players[i].id);
            players[j].draw();
        }
    }
    drawHud();
}

function drawBackground(){
    backgroundHorizontalSize = 5;
    backgroundVerticalSize = 4;
    for (var i = 0; i < backgroundHorizontalSize; i++) {
        for (var j = 0; j < backgroundVerticalSize; j++) {
            if (i % 2 == 0){
                ctx.drawImage(images["backsheet1"], 0, 0, maxBackGrid, maxBackGrid, (i * backGrid) - backOffset, (j * backGrid) - backOffset, maxBackGrid, maxBackGrid);
            }else{
                ctx.drawImage(images["backsheet1"], maxBackGrid, 0, maxBackGrid, maxBackGrid, (i * backGrid) - backOffset, (j * backGrid) - backOffset, maxBackGrid, maxBackGrid);
            }
        }
    }
}

function drawWorld() {
    mapHorizontalSize = level.map.length;
    mapVerticalSize = level.map[0].length;
    for (var i = 0; i < mapHorizontalSize; i++) {
        for (var j = 0; j < mapVerticalSize; j++) {
            var t = level.map[i][j];
            var tnum = parseInt(t.substr(1, 2));
            switch (t.charAt(0)) {
                case 'w':
                    drawGridObject(images["spritesheet1"], tnum, 1, (i * grid) - offSet, (j * grid) - offSet);
                    break;
                case 'h':
                    drawGridObject(images["spritesheet1"], tnum + 4, 1, (i * grid) - offSet, (j * grid) - offSet);
                    break;
                case 'e':
                    drawGridObject(images["spritesheet1"], tnum, 0, (i * grid) - offSet, (j * grid) - offSet);
                    break;
            }
        }
    }
}

function drawHud() {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);

    //FPS
    ctx.fillStyle = "#000";
    ctx.font = "bold 12px sans-serif";
    ctx.fillText("fps: " + curFPS + "/" + FPSlimit, 10, 20);
    ++numFramesDrawn;

    ctx.restore();
}

function drawLoading() {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = "#FFF";

    ctx.font = 'bold 30px sans-serif';
    ctx.lineWidth = 1;
    ctx.strokeStyle = "#000";
    var dots = "";
    for (var i = 1; i < (numFramesDrawn / 15 % 30); i++) {
        dots += ".";
        if (i > 2) {
            break;
        }
    }
    var numResourcesLoaded = 0;
    var totalResources = 1;
    ctx.fillText('Loading' + dots, canvas.width / 2 - 50, canvas.height / 2 - 20);
    ctx.strokeText('Loading' + dots, canvas.width / 2 - 50, canvas.height / 2 - 20);
    ctx.fillText(numResourcesLoaded + "/" + totalResources, canvas.width / 2 - 15, canvas.height / 2 + 10);
    ctx.strokeText(numResourcesLoaded + "/" + totalResources, canvas.width / 2 - 15, canvas.height / 2 + 10);
    ++numFramesDrawn;

    ctx.restore();
}

function clear() {
    // Store the current transformation matrix
    ctx.save();
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Restore the transform
    ctx.restore();
}